package com.litong.rms.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.litong.rms.dao.BaseDao;

public class BaseDaoImpl  extends HibernateDaoSupport implements BaseDao,Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7489119577375140123L;


	public <T> void save(T entity) {
		try {
			this.getHibernateTemplate().save(entity);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}	
		
	}
	
	
	@SuppressWarnings("unchecked")
	public <T> List<T> find(String queryString,Object[] values) {	
		try {
			return (List<T>)this.getHibernateTemplate().find(queryString, values);
		} catch (DataAccessException e) {
			e.printStackTrace();
			return null;
		}
		
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> find(String queryString, Object value) {
		try {
			return (List<T>)this.getHibernateTemplate().find(queryString, value);
		} catch (DataAccessException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public <T> void saveOrUpdate(T entity) {
		try{
			this.getHibernateTemplate().saveOrUpdate(entity);
		}catch(DataAccessException e){
			e.printStackTrace();
		}
		
	}


	public <T> void delete(T entity) {
		try {
			this.getHibernateTemplate().delete(entity);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		
	}


	@SuppressWarnings("unchecked")
	public <T> List<T> getEntityList(String queryString) {
		try {
			return this.getHibernateTemplate().find(queryString);
		} catch (DataAccessException e) {
			e.printStackTrace();
			return null;
		}
		 
	}
	
	public void executeBySQL(final String queryString) {
		try {
			getHibernateTemplate().execute(
					new HibernateCallback() {
						public Object doInHibernate(Session session)
								throws HibernateException, SQLException {
							Query query = session.createSQLQuery(queryString);
							int i = query.executeUpdate();
							return i;
						}
					});
			
		} catch (RuntimeException re) {
			re.printStackTrace();
			//log.error("executeBySQL failed", re);
		}
	}
	


	
	
	
	
	
}
